package com.chmingx.JavaBasic.thread.forkjoin;

import java.util.concurrent.RecursiveTask;

public class MyTask extends RecursiveTask<Integer> {
    // 计算一列数，拆分成差值不能超过10，计算10以内运算的任务
    private static final Integer VALUE = 10;
    private int begin;
    private int end;
    private int result;

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if ((end - begin) <= VALUE) {
            for (int i = begin; i <= end; i++) {
                result += i;
            }
        }else {
            int middle = (begin + end) / 2;
            // 拆分
            MyTask myTask01 = new MyTask(begin, middle);
            MyTask myTask02 = new MyTask(middle + 1, end);
            // 调用拆分方法
            myTask01.fork();
            myTask02.fork();
            // 合并结果
            result = myTask01.join() + myTask02.join();
        }
        return result;
    }
}
